package com.artfii.fluentsql.core.jdbc;

import java.sql.Connection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * ConnectionBuilder，创建connection,并且提供从缓存里取得connection
 */
public interface ConnectionBuilder {

    Map<SqlEngine, Connection> base_connection = new HashMap<>(10);//初始的连接
    Set<FluentConnection> connection_pool = new HashSet<>(50); //连接pool

    /**
     * 通过配置文件创建连接
     *
     * @param provider 连接供应商,方便框架接管,实现事务管理
     * @param config   FluentSql的基础配置
     * @return
     */
    Connection buildConnection(ConnectionProvider provider, FluentSqlConfig config);

    /**
     * 从连接池里取得 connection
     * @param isReadOnly
     * @return
     */
    static FluentConnection getConnectionOfPool(boolean isReadOnly) {
        FluentConnection fluentConnection = null;
        if(ConnectionBuilder.connection_pool.size() == 0) {
            fluentConnection = ConnectionBuilder.getBaseConnection(false);
        }else {
            for (FluentConnection conn : ConnectionBuilder.connection_pool) {
                if (conn.isClosed()) {
                    continue;
                }
                fluentConnection = conn;
                break;
            }
            if(null == fluentConnection){
                fluentConnection = getBaseConnection(isReadOnly);
            }
        }
        return fluentConnection;
    }

    static FluentConnection getBaseConnection(boolean isReadOnly) {
        FluentConnection baseConnection = (FluentConnection) ConnectionBuilder.base_connection.get(ConnectionBuilder.SqlEngine.fluentsql);
        FluentConnection newConn = baseConnection.getCurrentConnection(isReadOnly);
        return newConn;
    }


    /**
     * 使用的底层SQL引擎，默认fluentsql
     */
    enum SqlEngine {
        fluentsql,
        sql20,
        spring_jdbc,
        spring_named_jdbc;
    }

}
